package com.futvan.z.framework.common.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.futvan.z.framework.common.bean.Code;
import com.futvan.z.framework.common.bean.Result;
import com.futvan.z.framework.common.service.CommonService;
import com.futvan.z.framework.core.SuperAction;
import com.futvan.z.framework.core.z;
import com.futvan.z.framework.util.StringUtil;
import com.futvan.z.system.zcode.z_code;
import com.futvan.z.system.zcode.z_code_detail;
import com.futvan.z.system.zform.z_form_table;
import com.futvan.z.system.zform.z_form_table_column;
import com.futvan.z.system.zhttpservices.z_http_services;
import com.futvan.z.system.zhttpservices.z_http_services_parameter;
/**
 * Z平台通用接口
 * @author z
 *
 */
@Controller
public class ZAction extends SuperAction {

	@Autowired
	private CommonService commonService;

	/**
	 * 通用表单列表查询接口
	 * @param bean
	 * @return
	 */
	@RequestMapping(value="/zservices_list",method=RequestMethod.GET)
	public @ResponseBody Result list(@RequestParam HashMap<String, String> bean) {
		Result result = new Result();
		Result authority = z.isServiceAuthority(bean,request);
		if(Code.SUCCESS.equals(authority.getCode())){
			if(z.isNotNull(bean.get("tableId"))) {
				z_form_table t = z.tables.get(bean.get("tableId"));
				if(z.isNotNull(t) && "1".equals(t.getIs_open_default_getservice())) {
					try {
						List<HashMap<String, Object>> list = commonService.selectListAll(bean);
						result.setCode(Code.SUCCESS);
						result.setData(list);
					} catch (Exception e) {
						result.setCode(Code.ERROR);
						result.setMsg(StringUtil.ExceptionToString(e));
					}
				}else {
					result.setCode(Code.ERROR);
					result.setMsg("该表单未开放默认查询接口访问权限");
				}
			}else {
				result.setCode(Code.ERROR);
				result.setMsg("tableId is null");
			}
		}else {
			result = authority;
		}
		return result;
	}

	

	/**
	 * 通用表单单条记录查询接口
	 * @param bean
	 * @return
	 */
	@RequestMapping(value="/zservices_one",method=RequestMethod.GET)
	public @ResponseBody Result one(@RequestParam HashMap<String, String> bean) {
		Result result = new Result();
		Result authority = z.isServiceAuthority(bean,request);
		if(Code.SUCCESS.equals(authority.getCode())){
			if(z.isNotNull(bean.get("tableId"))) {
				z_form_table t = z.tables.get(bean.get("tableId"));
				if(z.isNotNull(t) && "1".equals(t.getIs_open_default_getservice())) {
					if(z.isNotNull(bean.get("zid"))) {
						try {
							List<HashMap<String,String>> list = commonService.selectList(bean);
							if(z.isNotNull(list)) {
								if(list.size()==1) {
									result.setCode(Code.SUCCESS);
									result.setData(list.get(0));
								}else {
									result.setCode(Code.ERROR);
									result.setMsg("查询记录数："+list.size());
								}
							}else {
								result.setCode(Code.ERROR);
								result.setMsg("返回结果集为空");
							}
						} catch (Exception e) {
							result.setCode(Code.ERROR);
							result.setMsg(StringUtil.ExceptionToString(e));
						}
					}else {
						result.setCode(Code.ERROR);
						result.setMsg("zid is null");
					}
				}else {
					result.setCode(Code.ERROR);
					result.setMsg("该表单未开放默认查询接口访问权限");
				}
			}else {
				result.setCode(Code.ERROR);
				result.setMsg("tableId is null");
			}
		}else {
			result = authority;
		}
		return result;
	}

	/**
	 * 通用表单记录删除接口
	 * @param bean
	 * @return
	 */
	@RequestMapping(value="/zservices_deleteByZid",method=RequestMethod.GET)
	public @ResponseBody Result deleteByZid(@RequestParam HashMap<String, String> bean) {
		Result result = new Result();
		Result authority = z.isServiceAuthority(bean,request);
		if(Code.SUCCESS.equals(authority.getCode())){
			if(z.isNotNull(bean.get("tableId"))) {
				z_form_table t = z.tables.get(bean.get("tableId"));
				if(z.isNotNull(t) && "1".equals(t.getIs_open_default_deleteservice())) {
					if(z.isNotNull(bean.get("zid"))) {
						int num = commonService.delete("delete from "+bean.get("tableId")+" where zid in("+StringUtil.ListToSqlInArray(bean.get("zid"))+")");
						if(num>0) {
							result.setCode(Code.SUCCESS);
							result.setMsg("成功删除"+num+"条记录");
						}else {
							result.setCode(Code.ERROR);
							result.setMsg("删除0条记录");
						}
					}else {
						result.setCode(Code.ERROR);
						result.setMsg("zid is null");
					}

				}else {
					result.setCode(Code.ERROR);
					result.setMsg("该表单未开放默认删除接口访问权限");
				}
			}else {
				result.setCode(Code.ERROR);
				result.setMsg("tableId is null");
			}
		}else {
			result = authority;
		}
		return result;
	}

	/**
	 * 通用表单数据保存方法
	 * @param bean
	 * @return
	 */
	@RequestMapping(value="/zservices_save")
	public @ResponseBody Result save(@RequestParam HashMap<String, String> bean) {
		Result result = new Result();
		Result authority = z.isServiceAuthority(bean,request);
		if(Code.SUCCESS.equals(authority.getCode())){
			if(z.isNotNull(bean.get("tableId"))) {
				z_form_table t = z.tables.get(bean.get("tableId"));
				if(z.isNotNull(t) && "1".equals(t.getIs_open_default_saveservice())) {
					try {
						if(z.isNull(bean.get("zid"))) {
							//新增
							result = commonService.insert(bean, request);
						}else {
							int num = commonService.selectInt("select count(*) from "+bean.get("tableId")+" where zid = '"+bean.get("zid")+"'");
							if(num==1) {
								//修改
								result = commonService.update(bean, request);
							}else if(num>1) {
								//出现多条
								result.setCode(Code.ERROR);
								result.setMsg("该zid对应记录出现两条，无法修改");
							}else {
								//未找到记录-执行新增
								result = commonService.insert(bean, request);
							}
						}
					} catch (Exception e) {
						result.setCode(Code.ERROR);
						result.setMsg(StringUtil.ExceptionToString(e));
					}
				}else {
					result.setCode(Code.ERROR);
					result.setMsg("该表单未开放默认保存接口访问权限");
				}
			}else {
				result.setCode(Code.ERROR);
				result.setMsg("tableId is null");
			}
		}else {
			result = authority;
		}
		return result;
	}

	@RequestMapping(value="/zservices_help",method=RequestMethod.GET)
	public ModelAndView help() {
		ModelAndView  model = new ModelAndView("common/main/services_list");
		List<z_http_services> sList = new ArrayList<z_http_services>();
		//便利定制接口
		for(Map.Entry<String, z_http_services> entry:z.httpservices.entrySet()) {
			sList.add(entry.getValue());
		}
		model.addObject("list", sList);

		//获取所有表单接口
		Map<String,List<z_http_services>> m = new HashMap<String, List<z_http_services>>();
		for (Map.Entry<String,z_form_table> entry : z.tables.entrySet()) {
			z_form_table t = entry.getValue();
			List<z_http_services> defaultList = new ArrayList<z_http_services>();
			if("1".equals(t.getIs_open_default_getservice())) {
				//创建List接口
				defaultList.add(CreateListHttpServicesBean(t));
				//创建One接口
				defaultList.add(CreateOneHttpServicesBean(t));
			}

			if("1".equals(t.getIs_open_default_deleteservice())) {
				//创建DeleteByZid接口
				defaultList.add(CreateDeleteByZidHttpServicesBean(t));
			}

			if("1".equals(t.getIs_open_default_saveservice())) {
				//创建Save接口
				defaultList.add(CreateSaveHttpServicesBean(t));
			}
			if(z.isNotNull(defaultList) && defaultList.size()>0) {
				m.put(t.getTable_id(), defaultList);
			}
		}
		TreeMap<String,List<z_http_services>> paramTreeMap = new TreeMap<String,List<z_http_services>>(m);
		model.addObject("defaultList", paramTreeMap);


		//获取服务器IP
		if("true".equals(z.sp.get("isSSL"))) {
			model.addObject("serverip", "https://"+z.sp.get("serverip")+"/");
		}else {
			model.addObject("serverip", "http://"+z.sp.get("serverip")+"/");
		}
		//获取参数类型值
		z_code ptype = z.code.get("services_parameter_type");
		Map<String,String> services_parameter_type_map = new HashMap<String,String>();
		for (z_code_detail cd : ptype.getZ_code_detail_list()) {
			services_parameter_type_map.put(cd.getZ_key(), cd.getZ_value());
		}
		model.addObject("parameter_type",services_parameter_type_map);

		return model;
	}

	private z_http_services CreateSaveHttpServicesBean(z_form_table table) {
		z_http_services service = new z_http_services();
		service.setNumber(table.getTable_id());
		service.setTitle("保存"+table.getTable_title()+"数据");
		service.setServiceid("zservices/save?tableId="+table.getTable_id());
		service.setZ_http_services_parameter_list(CreateServicesParameterListBean(table));
		return service;
	}

	private z_http_services CreateDeleteByZidHttpServicesBean(z_form_table table) {
		z_http_services service = new z_http_services();
		service.setNumber(table.getTable_id());
		service.setTitle("删除"+table.getTable_title()+"数据");
		service.setServiceid("zservices/deleteByZid?tableId="+table.getTable_id());
		List<z_http_services_parameter> list_service_parameter_list = new ArrayList<z_http_services_parameter>();
		z_http_services_parameter tableid = new z_http_services_parameter();
		tableid.setName("zid");
		tableid.setTitle("主键【多条数据删除可以逗号分隔】");
		tableid.setServices_parameter_type("0");
		list_service_parameter_list.add(tableid);
		service.setZ_http_services_parameter_list(list_service_parameter_list);
		return service;
	}

	private z_http_services CreateOneHttpServicesBean(z_form_table table) {
		z_http_services service = new z_http_services();
		service.setNumber(table.getTable_id());
		service.setTitle("获取"+table.getTable_title()+"单条数据");
		service.setServiceid("zservices/one?tableId="+table.getTable_id());
		List<z_http_services_parameter> list_service_parameter_list = new ArrayList<z_http_services_parameter>();
		z_http_services_parameter tableid = new z_http_services_parameter();
		tableid.setName("zid");
		tableid.setTitle("主键");
		tableid.setServices_parameter_type("0");
		list_service_parameter_list.add(tableid);
		service.setZ_http_services_parameter_list(list_service_parameter_list);
		return service;
	}

	private z_http_services CreateListHttpServicesBean(z_form_table table) {
		z_http_services service = new z_http_services();
		service.setTitle("获取"+table.getTable_title()+"列表数据");
		service.setServiceid("zservices/list?tableId="+table.getTable_id());
		service.setNumber(table.getTable_id());
		service.setZ_http_services_parameter_list(CreateServicesParameterListBean(table));
		return service;
	}

	/**
	 * 生成接口参数列表数据
	 * @param table
	 * @return
	 */
	private List<z_http_services_parameter> CreateServicesParameterListBean(z_form_table table) {
		List<z_http_services_parameter> list_service_parameter_list = new ArrayList<z_http_services_parameter>();
		List<z_form_table_column> columnList = table.getZ_form_table_column_list();
		for (z_form_table_column column : columnList) {
			z_http_services_parameter tableid = new z_http_services_parameter();
			tableid.setName(column.getColumn_id());
			tableid.setTitle(column.getColumn_name());
			tableid.setServices_parameter_type("0");
			list_service_parameter_list.add(tableid);
		}
		return list_service_parameter_list;
	}
}
